<?php
define('IN_ROSTER', true);
//require_once ('../settings.php');

require_once (ROSTER_LIB . 'update.lib.php');
$update = new update();
require_once (ROSTER_LIB . 'item.php');
class apiUpdate
{
	var $memberID;
	var $guildID;
	var $data=array();
	var $upd;
	var $cname;
	var $cserver;
	var $factionID;
	var $factionEN = array(0 => 'Alliance',
	1 => 'Horde');
	var $raceidtofaction = array(
	1 => 0,
	2 => 1,
	3 => 0,
	4 => 0,
	5 => 1,
	6 => 1,
	7 => 0,
	8 => 1,
	10 => 1,
	11 => 0,
	22 => 0,
	9 => 1,
);
	var $active_member = array();
	var $status = array(	'guildInfo' => 0,
							'characterInfo' => 0,
							'skillInfo' => 0,
							'reputationInfo' => 0,
							'equipmentInfo' => 0,
							'talentInfo' => 0,
							'achievementInfo' => 0,
						);
	var $message;
	var $spells = array();
	var $local;
	Var $region;
	
	public function __construct($region)
	{
		$this->region = (isset($region) ? $region : 'us');
		$this->local = strtoupper((isset($region) ? $region : 'us'));
	}
	
	function return_gender($genderid) {
		if ($genderid == "0") {$gender = "Male";}
		if ($genderid == "1") {$gender = "Female";}
		return $gender;
	}

//processs player data

	function getplayerid($n,$s)
	{
		global $roster, $update;
		
		$sqlquery2 = "SELECT member_id FROM `api_players` WHERE `name` = '" . $roster->db->escape($n) . "' AND `server` = '" . $roster->db->escape($s) . "'";
		$result2 = $roster->db->query($sqlquery2);
		$row = $roster->db->fetch($result2);
		///echo '++++'.$row['member_id'].'++++<br>';
		return $row['member_id'];
	}
	function getguild_info($n,$s)
	{
		global $roster, $update;
		
		$sqlquery2 = "SELECT * FROM `api_guilds` WHERE `guild_name` = '" . $roster->db->escape($n) . "' AND `server` = '" . $roster->db->escape($s) . "'";
		$result2 = $roster->db->query($sqlquery2);
		$row = $roster->db->fetch($result2);
		if ($result2)
		{
			return $row;
		}
		else
		{
			return false;
		}
	}

	function update_player($char,$guildid ='0')
	{
		global $roster, $update;
		//echo '<pre>';
		//print_r($char);
		
		
		$this->cname = $char['name'];
		$this->cserver =$char['realm'];
		$this->memberID = $this->getplayerid($char['name'],$char['realm']);
		$factionid = $this->raceidtofaction[$char['race']];
		$this->factionID = array('id'=>$this->raceidtofaction[$char['race']],'en'=>$this->factionEN[$factionid]);
		
		//$this->updateplayerguild($char['guild']);
		if (isset($char['guild']['name']))
		{
			$g = $this->getguild_info( $char['guild']['name'],$char['realm']);
			$this->updateplayerguild($char['guild'],$g);
			$g = $this->getguild_info( $char['guild']['name'],$char['realm']);
			$guildid = $g['guild_id'];
		}
		
		$update->reset_values();
		$update->add_value('name', $char['name'] );
		$update->add_value('guild_id',($g['guild_id'] != '0' ? $g['guild_id'] : $guildid) );
		$update->add_value('dateupdatedutc', time() );
		$update->add_value('guild', $char['guild']['name'] );
		$update->add_value('race', $roster->locale->act['id_to_race'][$char['race']] );
		$update->add_value('raceid', $char['race'] );
		$update->add_value('raceEn', $roster->locale->act['race_to_en'][$roster->locale->act['id_to_race'][$char['race']]] );
		$update->add_value('class', $roster->locale->act['id_to_class'][$char['class']] );
		$update->add_value('classid', $char['class'] );
		$update->add_value('classEn', $roster->locale->act['class_to_en'][$roster->locale->act['id_to_class'][$char['class']]] );
		$update->add_value('factionID', $this->raceidtofaction[$char['race']] );
		$update->add_value('factionEN', $this->factionEN[$this->raceidtofaction[$char['race']]] );
		$update->add_value('sex', $this->return_gender($char['gender']) );
		$update->add_value('sexid', $char['gender'] );
		$update->add_value('level', $char['level'] );
		$update->add_value('server', $char['realm'] );
		$update->add_value('region', $this->local );
		$update->add_value('thumbnail', $char['thumbnail'] );
		$update->add_value('achievementPoints', $char['achievementPoints'] );
	
		foreach ($char['stats'] as $var => $info)
		{	
			$update->add_value($var, $info );
		}
		
		if( isset($this->memberID) )
		{
			$querystr = "UPDATE `api_players` SET " . $update->assignstr . " WHERE `member_id` = '".$this->memberID."';";
			$this->upd = true;
		}
		else
		{
			$querystr = "INSERT INTO `api_players` SET " . $update->assignstr . ";";
		}
		//echo $querystr.'<br>';
		//final force check
		if (isset($char['name']) && $char['name'] != '')
		{
			$ret = $roster->db->query($querystr);
			$this->status['characterInfo'] = 1;
		}
		else
		{
			$this->status['characterInfo'] = 0;
			return false;
		}

		if( !isset($this->memberID) )
		{
			$this->memberID = $this->getplayerid($char['name'],$char['realm']);
		}
		//echo $this->memberID.' - '.$querystr.'<br>';
		$this->update_talents($char);
		// disabled to save db space untill achievement db is full
		//$this->update_achievements($char);
		$this->update_reputation($char);
		$this->update_raid($char);
		$this->update_equipment($char['items']);
		//$this->update_crit($char);
		$this->update_companions($char);
		//$res = array('stoptime'=>,'status'=>$this->status);

		return $this->status;
		
	}
	
	function updateplayerguild($guild, $g)
	{
		global $roster, $update;
		$update->reset_values();
		$update->add_value('guild_name', $guild['name'] );
		$update->add_value('update_time', time() );
		$update->add_value('server', $guild['realm'] );
		$update->add_value('region', $this->local );
		$update->add_value('guild_level', $guild['level'] );
		$update->add_value('factionEn', $this->factionID['en']);
		$update->add_value('faction', $this->factionID['id']);
		$update->add_value('guild_num_members',$guild['members'] );
		$update->add_value('achievementPoints', $guild['achievementPoints'] );
		/*
		  "emblem":{
			"icon":143,
			"iconColor":"ffdfa55a",
			"border":-1,
			"borderColor":"fff9cc30",
			"backgroundColor":"ff860f9a"
	emblem_icon  emblem_icon_color  emblem_border  emblem_border_color  emblem_bg_color 
		*/
		if($guild['emblem']['icon']<10)
		{
			$num = "0".$guild['emblem']['icon']; 
		}else{
			$num = $guild['emblem']['icon'];
		}
		$update->add_value('emblem_icon', $num );
		$update->add_value('emblem_icon_color', $guild['emblem']['iconColor'] );
		$update->add_value('emblem_border', (($guild['emblem']['border']== -1) ? '00' : "0".$guild['emblem']['border']) );
		$update->add_value('emblem_border_color', $guild['emblem']['borderColor'] );
		$update->add_value('emblem_bg_color', $guild['emblem']['backgroundColor'] );
		
		if( isset($g['guild_id']) )
		{
			$querystr = "UPDATE `api_guilds` SET " . $update->assignstr . " WHERE `guild_id` = '".$g['guild_id']."';";
			$this->upd = true;
			$this->status['guildInfo'] = 1;
		}
		else
		{
			$querystr = "INSERT INTO `api_guilds` SET " . $update->assignstr . ";";
			$this->status['guildInfo'] = 1;
		}

		$ret = $roster->db->query($querystr);
		if (!ret)
		{
			$this->status['guildInfo'] = false;
		}
	}
	function update_talents($char)
	{
		global $roster, $update;
		$sqlquery2 = "DELETE FROM `api_talent_builds` WHERE `member_id` = '$this->memberID'";
		$result2 = $roster->db->query($sqlquery2);
		$querystr = "DELETE FROM `api_glyphs` WHERE `member_id` = '$this->memberID';";
		$roster->db->query($querystr);
		$talentBuildData=array();
		foreach ($char['talents'] as $key => $spec)
		{
			if (isset($spec['selected']) && $spec['selected'] ==1 )
			{
				$branch = '0';
				$g = '';
				//$talentBuildData['1'] = $spec['build'];//'';
				$i=0;
				foreach ($spec['trees'] as $r => $e)
				{$i++;
					$g[$i] = $e['total'];
				}
				$talentBuildData[$branch] = array(
							'build'=>$spec['build'],
							'spec_icon'=>$spec['icon'],
							'spec_name'=>$spec['name'],
							'spec_build'=>''.$g[1].'/'.$g[2].'/'.$g[3].'');
			}
			else
			{
				if ($spec['build'] != '0000000000000000000000000000000000000000000000000000000000')
				{
					$branch = '1';
					$g = '';
					//$talentBuildData['1'] = $spec['build'];//'';
					$i=0;
					foreach ($spec['trees'] as $r => $e)
					{$i++;
						$g[$i] = $e['total'];
					}
					$talentBuildData[$branch] = array(
							'build'=>$spec['build'],
							'spec_icon'=>$spec['icon'],
							'spec_name'=>$spec['name'],
							'spec_build'=>''.$g[1].'/'.$g[2].'/'.$g[3].''
					);
				}
			}

			foreach ($spec['glyphs'] as $a => $gl)
			{
				foreach($gl as $xx =>$glyph)
				{
				$values = array(
					'member_id'		=> $this->memberID,
					'glyph_type'	=> $this->glyphtype($a),
					'glyph_build'	=> $branch,
					'glyph_id'		=> $glyph['glyph'],
					'glyph_itemid'	=> $glyph['item']
				);

				$querystr = "INSERT INTO `api_glyphs` "
					. $roster->db->build_query('INSERT', $values) . ";";
				$result = $roster->db->query($querystr);
				}
			}
			
		}
		sort($talentBuildData);
		$t = 0;
		foreach( $talentBuildData as $build => $talentData )
		{
			$update->reset_values();
			$update->add_value('build', $build);
			$update->add_value('member_id', $this->memberID);
			$update->add_value('tree', $talentData['build']);
			$update->add_value('spec_name', $talentData['spec_name']);
			$update->add_value('spec_icon', $talentData['spec_icon']);
			$update->add_value('spec_build', $talentData['spec_build']);
			$querystr = "INSERT INTO `api_talent_builds` SET " . $update->assignstr;
			$t++;
			$result = $roster->db->query($querystr);
			if ($result)
			{
				$this->status['talentInfo']++;
			}

		}
		
	}
	
	
	function update_achievements($char)
	{
		global $roster, $update;
		
		$achi = $char['achievements'];
		$a = true;
		$sqlquery2 = "DELETE FROM `api_achievements` WHERE `member_id` = '$this->memberID'";
		$result2 = $roster->db->query($sqlquery2);

		foreach ($achi['achievementsCompleted'] as $var => $info)
		{	//echo $var.'<br>';
			$update->reset_values();
			$update->add_value('achie_id', $info );
			$update->add_value('achie_date', $char['achievements']['achievementsCompletedTimestamp'][''.$var.''] );

			$update->add_value('member_id', $this->memberID);
			$querystr = "INSERT INTO `api_achievements` SET " . $update->assignstr;
			//echo $querystr.'<br>';
			$result = $roster->db->query($querystr);
			if ($result)
			{
				$this->status['achievementInfo']++;
			}
			
		}
	}
	
	function update_crit($char)
	{
		global $roster, $update;
		
		$achi = $char['achievements'];
		$a = true;
		$sqlquery2 = "DELETE FROM `api_criteria` WHERE `member_id` = '$this->memberID'";
		$result2 = $roster->db->query($sqlquery2);

		foreach ($achi['criteria'] as $var => $info)
		{	//echo $var.'<br>';
			$update->reset_values();
			$update->add_value('member_id', $this->memberID );
			$update->add_value('crit_id', $info );

			$update->add_value('crit_date', $char['achievements']['criteriaTimestamp'][''.$var.'']);
			$update->add_value('crit_value', $char['achievements']['criteriaQuantity'][''.$var.'']);
			$querystr = "INSERT INTO `api_criteria` SET " . $update->assignstr;
			$result = $roster->db->query($querystr);
		}
		//echo $sql.'<br>';
		
	}
	
	function update_reputation($char)
	{
		global $roster, $update;
		$sqlquery2 = "DELETE FROM `api_reputation` WHERE `member_id` = '$this->memberID'";
		$result2 = $roster->db->query($sqlquery2);
		foreach ($char['reputation'] as $var => $info)
		{	//echo $var.'<br>';
			$update->reset_values();
			$update->add_value('name', $info['name'] );
			$update->add_value('standing', $info['standing'] );
			$update->add_value('value', $info['value'] );
			$update->add_value('max', $info['max']);
			$update->add_value('member_id', $this->memberID);
			$querystr = "INSERT INTO `api_reputation` SET " . $update->assignstr;
			//echo $querystr.'<br>';
			$result = $roster->db->query($querystr);
			if ($result)
			{
				$this->status['reputationInfo']++;
			}
		}
		
	}
	
	
	function update_raid($char)
	{
		global $roster, $update;
		
		
		$proData = $char['progression']['raids'];
		if (is_array($proData))
		{
		$sqlquery2 = "DELETE FROM `api_raid` WHERE `member_id` = '$this->memberID'";
		$result2 = $roster->db->query($sqlquery2);
			foreach ($proData as $idx => $raid)
			{

				$update->reset_values();
				$update->add_value('raid', $raid['name'] );
				$update->add_value('raid_index', $idx );
				$update->add_value('nkills', $raid['normal'] );
				$update->add_value('hkills', $raid['heroic'] );
				$update->add_value('parent', '0' );
				$update->add_value('member_id', $this->memberID);
				$querystr = "INSERT INTO `api_raid` SET " . $update->assignstr;
				//echo $querystr.'<br>';
				$result = $roster->db->query($querystr);
				$b = 0;
				foreach($raid['bosses'] as $bid => $boss)
				{
					$b++;
					$update->reset_values();
					$update->add_value('raid', $raid['name'] );
					$update->add_value('raid_index', $idx );
					$update->add_value('nkills', $boss['normalKills'] );
					$update->add_value('hkills', $boss['heroicKills'] );
					$update->add_value('parent', $raid['name'] );
					$update->add_value('boss', $boss['name'] );
					$update->add_value('boss_index', $b );
					$update->add_value('member_id', $this->memberID);
					$querystr = "INSERT INTO `api_raid` SET " . $update->assignstr;
					//echo $querystr.'<br>';
					$result = $roster->db->query($querystr);
				}

			}

		}

	}
	
	function update_equipment($array)
	{
		global $roster, $update,$api;
		$sqlquery2 = "DELETE FROM `api_items` WHERE `member_id` = '$this->memberID'";
		$result2 = $roster->db->query($sqlquery2);
		foreach($array as $slot => $eq)
		{
			$eqip = array();

			if ($slot != 'averageItemLevel' && $slot != 'averageItemLevelEquipped')
			{

				$tip = '';//str_replace($string, '', $x);
				$gam = null;
				$gam = array();
				foreach ($eq['tooltipParams'] as $ge => $id)
				{
					$gam[$ge] = $id;
				}
				$enchant = $gam['enchant'] ? $gam['enchant'] : '0';
				$gem0 = $gam['gem0'] ? $gam['gem0'] : '0';
				$gem1 = $gam['gem1'] ? $gam['gem1'] : '0';
				$gem2 = $gam['gem2'] ? $gam['gem2'] : '0';
				$es = $gam['extraSocket'] ? true : false;
				$gam = null;
				
				
				$sqlquery2 = "SELECT * FROM `api_item_cache` WHERE `item_id` = '".$eq['id']."'";
				$result2 = $roster->db->query($sqlquery2);
				$row = $roster->db->fetch($result2);
				$row['item_id'] = ''.$eq['id'].':'.$enchant.':'.$gem0.':'.$gem1.':'.$gem2.':0:0:1331630912:85:0';
				$xx = item::fetchOneMemberItemIDD( $row, '58124:0:52268:0:0:0:0:1331630912:85:0', 'full' );
				//echo $xx->html_tooltip;
				$tip = $xx->html_tooltip;//$api->Data->getItemtooltip($this->cname,$eq['id'],$gem0,$gem1,$gem2,$enchant,$es);//;
				
				$slot = ucwords($slot);
				$update->reset_values();
				//$eqip = array(
				$update->add_value('item_name' , $eq['name']);
				$update->add_value('item_parent' , 'equip');
				$update->add_value('item_slot' , $slot);
				$update->add_value('item_color' , $this->_setQualityc( $eq['quality'] ));
				$update->add_value('item_id' , ''.$eq['id'].':'.$enchant.':'.$gem0.':'.$gem1.':'.$gem2.':0:0:1331630912:85:0');
				$update->add_value('item_texture' , $eq['icon']);
				$update->add_value('item_rarity' , $eq['quality']);
				$update->add_value('item_tooltip' , $tip);
				$update->add_value('member_id', $this->memberID);
				$querystr = "INSERT INTO `api_items` SET " . $update->assignstr;
				//echo $querystr.'<br>';
				$result = $roster->db->query($querystr);
				if ($result)
				{
					$this->status['equipmentInfo']++;
				}
			}
		}
	}
	
	function update_companions($char)
	{
		global $roster, $update,$api;
		$querystr = "DELETE FROM `api_companions` WHERE `member_id` = '$this->memberID';";
		$roster->db->query($querystr);
		$tyye = array('Mount'=>'mounts','Critter'=>'companions');
		foreach ($tyye as $type => $ty)
		{
			//echo $ty.'<br>';
			foreach( $char[$ty] as $id => $data )
			{
				$spell = $this->getspalldata($data);
				$update->reset_values();
				$update->add_value('member_id', $this->memberID);
				$update->add_value('name', $spell['name']);
				$update->add_value('type', $type);
				$update->add_value('slot', $id);
				$update->add_value('spellid', $data);
				$update->add_value('tooltip', $spell['tooltip']);
				if( !empty($spell['icon']) )
				{
					$update->add_value('icon', $spell['icon'] );
				}
				$querystr = "INSERT INTO `api_companions` SET " . $update->assignstr . ";";
				$result = $roster->db->query($querystr);
				if( !$result )
				{
					//$this->setError('Companion [' . $spells[$data]['Name'] . '] could not be inserted',$roster->db->error());
				}
			}
		}
	
	}
	
	// heres a resorce biutch ...
	function getspalldata($data)
	{
		global $roster, $addon;
		$query = "SELECT * FROM `api_spell_cache` WHERE `spell_id` ='$data'";
		$result = $roster->db->query($query);
		$d = array();
		while ($row = $roster->db->fetch($result))
		{
			//spell_id  spell_name  spell_color  spell_texture  spell_tooltip  
			$d = array(
				'id' => $row['spell_id'],
				'name' => $row['spell_name'],
				'icon' => $row['spell_texture'],
				'tooltip' => $row['spell_tooltip']			
			);
		}
		return $d;
	}
	
	function _setQualityc( $color )
	{
		$ret = '';
		switch ($color) {
			case 5: $ret = "ff8000"; //Orange
				break;
			case 4: $ret = "a335ee"; //Purple
				break;
			case 3: $ret = "0070dd"; //Blue
				break;
			case 2: $ret = "1eff00"; //Green
				break;
			case 1: $ret = "ffffff"; //White
				break;
			default: $ret = "9d9d9d"; //Grey
				break;
		}
		return $ret;
	}
	function _setQualityn( $color )
	{
		switch( strtolower( $color ) )
		{
			case '6':
				$quality_id = '6';
				$quality = 'heirloom';
				break;
			case '5':
				$quality_id = '5';
				$quality = 'legendary';
				break;
			case '4':
				$quality_id = '4';
				$quality = 'epic';
				break;
			case '3':
				$quality_id = '3';
				$quality = 'rare';
				break;
			case '2':
				$quality_id = '2';
				$quality = 'uncommon';
				break;
			case '1':
				$quality_id = '1';
				$quality = 'common';
				break;
			case '0':
				$quality_id = '0';
				$quality = 'poor';
				break;
			default:
				$quality_id = '0';
				$quality = 'none';
				break;
		}
		return $quality;
	}
	function glyphtype($name)
	{
		switch( strtolower( $name ) )
		{
			case 'prime':
				$quality_id = '3';
				$quality = 'uncommon';
				break;
			case 'major':
				$quality_id = '2';
				$quality = 'common';
				break;
			case 'minor':
				$quality_id = '1';
				$quality = 'poor';
				break;
			default:
				$quality_id = '0';
				$quality = 'none';
				break;
		}
		return $quality_id;
	}
	
	
		
}	

?>